from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query, Body
from sqlalchemy.orm import Session
from sqlalchemy import and_, or_, desc, asc, func
from pydantic import BaseModel, Field
from models.tools import DisableToolRequest
from utils.files import safe_replace_file
from database.connection import get_db
from database.models import Tools, Tools_type
from models.tools import (
    ToolsCreate, ToolsUpdate, ToolsResponse, ToolsListResponse, 
    ToolsQuery, ToolsClickRequest
)
from utils.auth import get_current_user_id, get_current_user

router = APIRouter(prefix="/tools", tags=["工具管理"])


@router.get("/categories", summary="获取工具分类列表")
async def get_tool_categories(
    db: Session = Depends(get_db)
):
    """
    获取所有工具分类
    从Tools_type表获取分类信息
    """
    try:
        categories = db.query(Tools_type).filter(
            Tools_type.is_active == True
        ).order_by(Tools_type.sort_order.asc()).all()
        
        category_list = [{
            "id": category.id,
            "name": category.name,
            "icon": category.icon,
            "sort_order": category.sort_order
        } for category in categories]
        
        return {
            "code": 200,
            "msg": "获取分类列表成功",
            "data": {"categories": category_list}
        }
    
    except Exception as e:
        return {
            "code": 500,
            "msg": f"获取分类列表失败: {str(e)}"
        }


@router.post("/categories", summary="添加工具分类")
async def create_tool_category(
    category_data: dict,
    db: Session = Depends(get_db),
    current_user: dict = Depends(get_current_user)
):
    """
    添加新的工具分类
    需要管理员权限
    """
    try:
        # 检查是否为管理员
        print(current_user, 333333)
        if current_user.get("role") != "admin":
            return {
                "code": 500,
                "msg": "权限不足，只有管理员可以添加分类"
            }
        
        # 检查分类名称是否已存在
        existing_category = db.query(Tools_type).filter(
            Tools_type.name == category_data.get("name")
        ).first()
        
        if existing_category:
            return {
                "code": 500,
                "msg": "分类名称已存在"
            }
        
        # 创建新分类
        new_category = Tools_type(
            name=category_data.get("name"),
            icon=category_data.get("icon", ""),
            sort_order=category_data.get("sort_order", 0),
            is_active=category_data.get("is_active", True)
        )
        
        db.add(new_category)
        db.commit()
        db.refresh(new_category)
        
        return {
            "code": 200,
            "msg": "添加分类成功",
            "data": {
                "id": new_category.id,
                "name": new_category.name,
                "icon": new_category.icon,
                "sort_order": new_category.sort_order,
                "is_active": new_category.is_active
            }
        }
    
    except Exception as e:
        db.rollback()
        return {
            "code": 500,
            "msg": f"添加分类失败: {str(e)}"
        }


@router.put("/categories/{category_id}", summary="修改工具分类")
async def update_tool_category(
    category_id: int,
    category_data: dict,
    db: Session = Depends(get_db),
    current_user: dict = Depends(get_current_user)
):
    """
    修改工具分类信息
    需要管理员权限
    """
    try:
        # 检查是否为管理员
        if current_user.get("role") != "admin":
            return {
                "code": 500,
                "msg": "权限不足，只有管理员可以修改分类"
            }
        
        # 查找要修改的分类
        category = db.query(Tools_type).filter(Tools_type.id == category_id).first()
        
        if not category:
            return {
                "code": 500,
                "msg": "分类不存在"
            }
        
        # 如果要修改名称，检查新名称是否已存在
        if "name" in category_data and category_data["name"] != category.name:
            existing_category = db.query(Tools_type).filter(
                Tools_type.name == category_data["name"],
                Tools_type.id != category_id
            ).first()
            
            if existing_category:
                return {
                    "code": 500,
                    "msg": "分类名称已存在"
                }
        
        # 更新分类信息
        if "name" in category_data:
            category.name = category_data["name"]
        if "icon" in category_data:
            safe_replace_file(category, 'icon', category_data["icon"])
        if "sort_order" in category_data:
            category.sort_order = category_data["sort_order"]
        if "is_active" in category_data:
            category.is_active = category_data["is_active"]
        
        db.commit()
        db.refresh(category)
        
        return {
            "code": 200,
            "msg": "修改分类成功",
            "data": {
                "id": category.id,
                "name": category.name,
                "icon": category.icon,
                "sort_order": category.sort_order,
                "is_active": category.is_active
            }
        }
    
    except Exception as e:
        db.rollback()
        return {
            "code": 500,
            "msg": f"修改分类失败: {str(e)}"
        }


@router.delete("/categories/{category_id}", summary="删除工具分类")
async def delete_tool_category(
    category_id: int,
    db: Session = Depends(get_db),
    current_user: dict = Depends(get_current_user)
):
    """
    删除工具分类
    需要管理员权限
    """
    try:
        # 检查是否为管理员
        if current_user.get("role") != "admin":
            return {
                "code": 500,
                "msg": "权限不足，只有管理员可以删除分类"
            }
        
        # 查找要删除的分类
        category = db.query(Tools_type).filter(Tools_type.id == category_id).first()
        
        if not category:
            return {
                "code": 500,
                "msg": "分类不存在"
            }
        
        # 检查该分类下是否还有工具
        tools_count = db.query(Tools).filter(Tools.category == category.name).count()
        
        if tools_count > 0:
            return {
                "code": 500,
                "msg": f"该分类下还有 {tools_count} 个工具，无法删除"
            }
        
        # 删除分类
        db.delete(category)
        db.commit()
        
        return {
            "code": 200,
            "msg": "删除分类成功"
        }
    
    except Exception as e:
        db.rollback()
        return {
            "code": 500,
            "msg": f"删除分类失败: {str(e)}"
        }


@router.get("/popular", summary="获取热门工具")
async def get_popular_tools(
    limit: int = Query(10, ge=1, le=50, description="返回数量"),
    db: Session = Depends(get_db)
):
    """
    获取热门工具列表
    按点击次数排序
    """
    try:
        tools = db.query(Tools).filter(
            Tools.is_active == True
        ).order_by(
            desc(Tools.click_count)
        ).limit(limit).all()
        
        return {
            "code": 200,
            "msg": "获取热门工具成功",
            "data": [ToolsResponse.from_orm(tool) for tool in tools]
        }
    
    except Exception as e:
        return {
            "code": 500,
            "msg": f"获取热门工具失败: {str(e)}"
        }


@router.post("/click", summary="记录工具点击")
async def record_tool_click(
    click_data: ToolsClickRequest,
    db: Session = Depends(get_db)
):
    """
    记录工具点击统计
    用于统计工具的使用情况
    """
    try:
        tool = db.query(Tools).filter(Tools.id == click_data.tool_id).first()
        if not tool:
            return {
                "code": 500,
                "msg": "工具不存在"
            }
        
        # 增加点击次数
        tool.click_count = (tool.click_count or 0) + 1
        db.commit()
        
        return {
            "code": 200,
            "msg": "点击记录成功",
            "data": {"click_count": tool.click_count}
        }
    
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        return {
            "code": 500,
            "msg": f"记录点击失败: {str(e)}"
        }


@router.get("/list", summary="获取工具列表")
async def get_tools_list(
    keyword: Optional[str] = Query(None, description="搜索关键词"),
    db: Session = Depends(get_db)
):
    """
    获取工具列表
    根据关键词查询active=1未禁用的AI工具，同一个分类的使用一个数组
    """
    try:
        # 构建查询条件 - 只查询启用的工具，联表查询获取分类排序信息
        query = db.query(Tools, Tools_type.sort_order).join(
            Tools_type, Tools.category == Tools_type.name
        ).filter(
            Tools.is_active == 1,
            Tools_type.is_active == True
        )
        
        # 关键词搜索 - 优化搜索逻辑
        if keyword:
            # 去除关键词前后空格并转换为小写进行模糊搜索
            keyword = keyword.strip()
            if keyword:  # 确保关键词不为空
                search_filter = or_(
                    Tools.title.ilike(f"%{keyword}%"),  # 不区分大小写的模糊搜索
                    Tools.description.ilike(f"%{keyword}%"),
                    Tools.category.ilike(f"%{keyword}%"),  # 添加分类字段搜索
                    Tools_type.name.ilike(f"%{keyword}%")  # 添加分类名称搜索
                )
                query = query.filter(search_filter)
        
        # 按分类排序字段和工具排序字段排序
        query = query.order_by(Tools_type.sort_order.asc(), Tools.sort_order.asc())
        
        # 获取符合条件的工具总数
        total_count = query.count()
        
        # 获取工具数据
        results = query.all()
        
        # 按分类分组，保持分类排序
        categories_dict = {}
        category_order = {}
        
        for tool, category_sort_order in results:
            category_name = tool.category
            if category_name not in categories_dict:
                categories_dict[category_name] = []
                category_order[category_name] = category_sort_order
            categories_dict[category_name].append(ToolsResponse.from_orm(tool))
        
        # 按分类排序转换为数组格式
        categories_list = []
        for category_name in sorted(categories_dict.keys(), key=lambda x: category_order[x]):
            categories_list.append({
                "category": category_name,
                "tools": categories_dict[category_name]
            })
        
        return {
            "code": 200,
            "msg": "获取工具列表成功",
            "data": {
                "total": total_count,
                "categories": categories_list
            }
        }
    
    except Exception as e:
        return {
            "code": 500,
            "msg": f"获取工具列表失败: {str(e)}"
        }


@router.post("/", summary="创建工具")
async def create_tool(
    tool_data: ToolsCreate,
    db: Session = Depends(get_db)
):
    """
    创建新工具
    自动设置sort_order为当前数据库中最大值+1
    """
    try:
        # 获取当前数据库中sort_order的最大值
        max_sort_order = db.query(func.max(Tools.sort_order)).scalar()
        
        # 如果数据库中没有记录或最大值为None，则从1开始
        next_sort_order = (max_sort_order or 0) + 1
        
        # 创建工具数据字典并自动设置sort_order
        tool_dict = tool_data.dict()
        tool_dict['sort_order'] = next_sort_order
        
        # 创建工具实例
        new_tool = Tools(**tool_dict)
        
        db.add(new_tool)
        db.commit()
        db.refresh(new_tool)
        
        return {
            "code": 200,
            "msg": "创建工具成功",
            "data": ToolsResponse.from_orm(new_tool)
        }
    
    except Exception as e:
        db.rollback()
        return {
            "code": 500,
            "msg": f"创建工具失败: {str(e)}"
        }


@router.get("/{tool_id}", summary="获取工具详情")
async def get_tool_detail(
    tool_id: int,
    db: Session = Depends(get_db)
):
    """
    根据ID获取工具详情
    """
    try:
        tool = db.query(Tools).filter(Tools.id == tool_id).first()
        if not tool:
            return {
                "code": 500,
                "msg": "工具不存在"
            }
        
        return {
            "code": 200,
            "msg": "获取工具详情成功",
            "data": ToolsResponse.from_orm(tool)
        }
    
    except HTTPException:
        raise
    except Exception as e:
        return {
            "code": 500,
            "msg": f"获取工具详情失败: {str(e)}"
        }


@router.put("/{tool_id}", summary="更新工具")
async def update_tool(
    tool_id: int,
    tool_data: ToolsUpdate,
    db: Session = Depends(get_db)
):
    """
    更新工具信息
    """
    try:
        tool = db.query(Tools).filter(Tools.id == tool_id).first()
        if not tool:
            return {
                "code": 500,
                "msg": "工具不存在"
            }
        
        # 更新字段
        update_data = tool_data.dict(exclude_unset=True)
        for field, value in update_data.items():
            if field == 'image':
                safe_replace_file(tool, 'image', value)
            else:
                setattr(tool, field, value)
        
        db.commit()
        db.refresh(tool)
        
        return {
            "code": 200,
            "msg": "更新工具成功",
            "data": ToolsResponse.from_orm(tool)
        }
    
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        return {
            "code": 500,
            "msg": f"更新工具失败: {str(e)}"
        }





@router.post("/disable", summary="启用/禁用工具")
async def disable_tool(
    request: DisableToolRequest,
    db: Session = Depends(get_db),
    current_user: dict = Depends(get_current_user)
):
    """
    启用/禁用工具（支持单个或批量操作）
    请求体参数：
    - tools_id: 工具ID，支持单个ID或逗号分隔的多个ID（如："1" 或 "1,2,3"）
    - status: 工具状态，0=禁用，1=启用
    需要token验证
    """
    try:
        print(request.status, 111111111111111)
        # 解析工具ID列表
        tool_ids_str = request.tools_id.split(',')
        tool_ids = []
        
        # 验证并转换ID为整数
        for id_str in tool_ids_str:
            id_str = id_str.strip()
            if not id_str:
                continue
            try:
                tool_ids.append(int(id_str))
            except ValueError:
                return {
                    "code": 400,
                    "msg": f"无效的工具ID: {id_str}"
                }
        
        if not tool_ids:
            return {
                "code": 400,
                "msg": "请提供有效的工具ID"
            }
        
        # 查询要操作的工具
        tools = db.query(Tools).filter(Tools.id.in_(tool_ids)).all()

        if not tools:
            return {
                "code": 500,
                "msg": "未找到要操作的工具"
            }
        
        # 检查是否所有工具都存在
        found_ids = [tool.id for tool in tools]
        if request.status == 1:
            # 批量启用工具
            db.query(Tools).filter(Tools.id.in_(found_ids)).update({"is_active": 1})
            db.commit()
            return {
                "code": 200,
                "msg": f"成功启用 {len(found_ids)} 个工具",
                "data": found_ids
            }

        if request.status == 0:

            # 批量禁用工具
            db.query(Tools).filter(Tools.id.in_(found_ids)).update({"is_active": 0})
            db.commit()
            return {
                "code": 200,
                "msg": f"成功禁用 {len(found_ids)} 个工具",
                "data": found_ids
            }

           
   
    
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        return {
            "code": 500,
            "msg": f"{('启用' if status == 1 else '禁用')}工具失败: {str(e)}"
        }


@router.delete("/{tool_id}", summary="删除工具")
async def delete_tool(
    tool_id: str,
    db: Session = Depends(get_db)
):
    """
    删除工具（支持单个或批量删除）
    tool_id: 工具ID，支持单个ID或逗号分隔的多个ID（如："1" 或 "1,2,3"）
    """
    try:
        # 解析工具ID列表
        tool_ids_str = tool_id.split(',')
        tool_ids = []
        
        # 验证并转换ID为整数
        for id_str in tool_ids_str:
            id_str = id_str.strip()
            if not id_str:
                continue
            try:
                tool_ids.append(int(id_str))
            except ValueError:
                return {
                    "code": 400,
                    "msg": f"无效的工具ID: {id_str}"
                }
        
        if not tool_ids:
            return {
                "code": 400,
                "msg": "请提供有效的工具ID"
            }
        
        # 查询要删除的工具
        tools = db.query(Tools).filter(Tools.id.in_(tool_ids)).all()
        
        if not tools:
            return {
                "code": 500,
                "msg": "未找到要删除的工具"
            }
        
        # 检查是否所有工具都存在
        found_ids = [tool.id for tool in tools]
        missing_ids = [tool_id for tool_id in tool_ids if tool_id not in found_ids]
        
        if missing_ids:
            return {
                "code": 500,
                "msg": f"以下工具不存在: {missing_ids}"
            }
        
        # 删除工具
        for tool in tools:
            db.delete(tool)
        
        db.commit()
        
        # 根据删除数量返回不同消息
        if len(tools) == 1:
            return {
                "code": 200,
                "msg": "工具删除成功"
            }
        else:
            return {
                "code": 200,
                "msg": f"成功删除 {len(tools)} 个工具",
                "deleted_count": len(tools)
            }
    
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        return {
            "code": 500,
            "msg": f"删除工具失败: {str(e)}"
        }